package jp.android_group.attender.android.ui;

/*
 * Copyright (c) 2009, "Japan Android Group Attender Team"
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

import java.io.FileNotFoundException;
import java.io.IOException;

import jp.android_group.attender.android.R;
import jp.android_group.attender.android.entity.ServerEntry;
import jp.android_group.attender.android.net.ServerInterface4Maimuzo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * 認証情報を設定する画面
 * 
 */
public class ServerSettingActivity extends BaseActivity implements
		OnClickListener {

	public static final String LOG_TAG = "LoginActivity";
	public static final boolean DEBUG_FLG = true;

	// 定数：初期化用リクエストコード
	public static final int REQUEST_CODE_INIT = 0x4f2039;

	// 定数：通常設定用リクエストコード
	public static final int REQUEST_CODE_EDIT = 0x86377e;
	public static final int REQUEST_CODE_ADD = 0xa454e;

	// 編集モード
	private int mMode = REQUEST_CODE_ADD;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		findViewById(R.id.login_btn_ok).setOnClickListener(this);
		findViewById(R.id.login_btn_cancel).setOnClickListener(this);
		((Spinner) findViewById(R.id.login_sp_server_type))
				.setOnItemSelectedListener(onServerTypeItemSelectedListener);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	public void onResume() {
		super.onResume();

		try {
			diaplay(ServerEntry.load(openFileInput(ServerEntry.FILE_NAME)));
		} catch (FileNotFoundException e) {
			if (DEBUG_FLG)
				Log.e(LOG_TAG, e.getMessage());
		} catch (IOException e) {
			if (DEBUG_FLG)
				Log.e(LOG_TAG, e.getMessage());
		} catch (ClassNotFoundException e) {
			if (DEBUG_FLG)
				Log.e(LOG_TAG, e.getMessage());
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 認証情報を表示
	 * 
	 * @param data
	 */
	private void diaplay(ServerEntry data) {
		((EditText) findViewById(R.id.login_et_label)).setText(data.getLabel());
		((EditText) findViewById(R.id.login_et_login_name)).setText(data
				.getLoginId());
		((EditText) findViewById(R.id.login_et_login_password)).setText(data
				.getPassword());
		((EditText) findViewById(R.id.login_et_base_url)).setText(data
				.getBaseUrl());

		if (data.getServerType() == ServerEntry.SERVER_TYPE_MAIMUZO_LEGACY) {
			((Spinner) findViewById(R.id.login_sp_server_type)).setSelection(0);
		} else if (data.getServerType() == ServerEntry.SERVER_TYPE_MAIMUZO_GAE) {
			((Spinner) findViewById(R.id.login_sp_server_type)).setSelection(1);
		} else if (data.getServerType() == ServerEntry.SERVER_TYPE_OTHERS) {
			((Spinner) findViewById(R.id.login_sp_server_type)).setSelection(2);
		}

		if (data.getProtocolType() == ServerEntry.PROTOCOL_TYPE_MAIMUZO) {
			((Spinner) findViewById(R.id.login_sp_protocol_type))
					.setSelection(0);
		} else if (data.getProtocolType() == ServerEntry.PROTOCOL_TYPE_SOAP1) {
			((Spinner) findViewById(R.id.login_sp_protocol_type))
					.setSelection(1);
		}
	}

	/**
	 * 入力内容から認証情報を生成
	 * 
	 * @return
	 */
	private ServerEntry generate() {

		ServerEntry result = new ServerEntry();
		result.setLabel(((EditText) findViewById(R.id.login_et_label))
				.getText().toString());

		int selectedServerType = ((Spinner) findViewById(R.id.login_sp_server_type))
				.getSelectedItemPosition();
		if (selectedServerType == 0) {
			result.setServerType(ServerEntry.SERVER_TYPE_MAIMUZO_LEGACY);
		} else if (selectedServerType == 1) {
			result.setServerType(ServerEntry.SERVER_TYPE_MAIMUZO_GAE);
		} else if (selectedServerType == 2) {
			result.setServerType(ServerEntry.SERVER_TYPE_OTHERS);
		}

		int selectedProtocolType = ((Spinner) findViewById(R.id.login_sp_protocol_type))
				.getSelectedItemPosition();
		if (selectedProtocolType == 0) {
			result.setProtocolType(ServerEntry.PROTOCOL_TYPE_MAIMUZO);
		} else if (selectedProtocolType == 1) {
			result.setServerType(ServerEntry.PROTOCOL_TYPE_SOAP1);
		}

		result
				.setProtocolType(((Spinner) findViewById(R.id.login_sp_protocol_type))
						.getSelectedItemPosition());
		result.setBaseUrl(((EditText) findViewById(R.id.login_et_base_url))
				.getText().toString());
		result.setLoginId(((EditText) findViewById(R.id.login_et_login_name))
				.getText().toString());
		result
				.setLoginPassword(((EditText) findViewById(R.id.login_et_login_password))
						.getText().toString());
		return result;
	}

	/**
	 * 入力内容を検証
	 * 
	 * @return
	 */
	private boolean validate(ServerEntry data) {

		boolean result = true;

		if (data.getLabel().equals("")) {
			Toast.makeText(this,
					getResources().getText(R.string.login_label_isnt_inputed),
					Toast.LENGTH_SHORT).show();
			return false;
		}

		if (data.getLoginId().equals("")) {
			Toast.makeText(this,
					getResources().getText(R.string.login_id_isnt_inputed),
					Toast.LENGTH_SHORT).show();
			return false;
		}

		if (data.getPassword().equals("")) {
			Toast.makeText(
					this,
					getResources()
							.getText(R.string.login_password_isnt_inputed),
					Toast.LENGTH_SHORT).show();
			return false;
		}

		return result;
	}

	/**
	 * 入力値を保存
	 */
	private void saveServerEntry() {

		// 入力内容から認証情報を生成
		ServerEntry data = generate();

		// 入力内容を検証
		if (validate(data) == true) {

			try {
				// ファイルに保存
				ServerEntry.save(openFileOutput(ServerEntry.FILE_NAME,
						MODE_PRIVATE), data);

			} catch (FileNotFoundException e) {
				if (DEBUG_FLG)
					Log.e(LOG_TAG, e.getMessage());
			} catch (IOException e) {
				if (DEBUG_FLG)
					Log.e(LOG_TAG, e.getMessage());
			}

			// DBに保存
			ServerEntry.save(data, mDb);

			// 呼び出し元アクティビティへデータを渡す
			Intent intent = new Intent();
			intent.putExtra(ServerEntry.class.getName(), data);
			setResult(Activity.RESULT_OK, intent);

			finish();

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {

		case R.id.login_btn_ok:
			// 入力値を保存
			saveServerEntry();
			break;

		case R.id.login_btn_cancel:
			setResult(Activity.RESULT_CANCELED);
			finish();
			break;

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * jp.android_group.attender.android.ui.BaseActivity#changeModeOffline(boolean
	 * )
	 */
	@Override
	protected void changeModeOffline(boolean mode) {
		// TODO Auto-generated method stub

	}

	private OnItemSelectedListener onServerTypeItemSelectedListener = new OnItemSelectedListener() {

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.widget.AdapterView.OnItemSelectedListener#onItemSelected(
		 * android.widget.AdapterView, android.view.View, int, long)
		 */
		@Override
		public void onItemSelected(AdapterView<?> arg0, View view, int arg2,
				long arg3) {

			// 新まいむぞうサーバーであれば
			if (arg2 == 0) {

				// 新まいむぞうサーバー用設定
				((EditText) findViewById(R.id.login_et_base_url))
						.setText(ServerInterface4Maimuzo.URI_BASE_GAE);
				((Spinner) findViewById(R.id.login_sp_protocol_type))
						.setSelection(0);
				findViewById(R.id.login_sp_protocol_type).setEnabled(false);
				findViewById(R.id.login_et_base_url).setEnabled(false);

				// それ以外
			} else {
				findViewById(R.id.login_sp_protocol_type).setEnabled(true);
				findViewById(R.id.login_et_base_url).setEnabled(true);
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.widget.AdapterView.OnItemSelectedListener#onNothingSelected
		 * (android.widget.AdapterView)
		 */
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * jp.android_group.attender.android.ui.BaseActivity#willConfirmWhenClosing
	 * ()
	 */
	@Override
	protected boolean willConfirmWhenClosing() {
		return false;
	}

}
